<?php 
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

//包含公用的方法 前台和后台公用
include __ROOT__."../include/function/common_function.php" ;  

/**
 * 后台常见的方法
 * author Cuil <lntschampion@163.com>
 */
 

//获取指定长度的随机字符串
function getRandChar($length) {

    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol) - 1;

    for ($i = 0; $i < $length; $i++) {
        //rand($min,$max)生成介于min和max两个数之间的一个随机整数
        $str .= $strPol[rand(0, $max)];
    }

    return $str;
}


/**
 * 缓存目录
 */
if (!function_exists('get_cache_key')){
	
	function get_cache_key($id,$key){
		
		$dir = dir_rule($id);
		$path = $dir;
		
		$date = date('Ymd',time());
		
		$dir = APPPATH.'cache/'.$date.'/'.$path;
		if (!file_exists($dir)) {
			@mkdir($dir,0777,true);
		}
		return $date.'/'.$path.$key;
	}
}

//获取积分的对称加密算法
class DES_ADMIN{

	static $key = '$&$(@*';
	static function encrypt($encrypt) {
		$key = self::$key;
		// 根据 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 加入 Padding
		$block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_ECB);
		$pad = $block - (strlen($encrypt) % $block);
		$encrypt .= str_repeat(chr($pad), $pad);
		// 不需要设定 IV 进行加密
	//	$passcrypt = mcrypt_encrypt(MCRYPT_DES, $key, $encrypt, MCRYPT_MODE_ECB);

		return base64_encode($encrypt);
	}
	static function decrypt($decrypt) {
		$key = self::$key;
		// 不需要设定 IV
		//$str = mcrypt_decrypt(MCRYPT_DES, $key, base64_decode($decrypt), MCRYPT_MODE_ECB);
        $str = base64_decode($decrypt);
		// 根据 PKCS#7 RFC 5652 Cryptographic Message Syntax (CMS) 修正 Message 移除 Padding
		$pad = ord($str[strlen($str) - 1]);
		return substr($str, 0, strlen($str) - $pad);
	}
}

/**
 *@记录系统操作日志文件到数据库里面 
 **sql 是要插入数据库中的 log_sql的值 
 *$action 动作
 *$person 操作人
 *$ip ip地址
 *status 操作是否成功 1成功 0失败
 *message 失败信息
 *groupname_ 定义数据库连接信息的时候的 groupname
 */
if(!function_exists("write_action_log") ){
	function write_action_log($sql,$url = '' ,$person = '' ,$ip = '',$status = '1' ,$message = '' , $groupname_ = "default"){
		if(!config_item('is_write_log_to_database')){//是否记录日志文件到数据表中
			return false ;
		}
		
		$sql = str_replace("\\", "", $sql); // 把\进行过滤掉
		$sql = str_replace("%", "\%", $sql); // 把 '%'前面加上\
		$sql = str_replace("'", "\'", $sql); // 把 ''过滤掉
		$message = daddslashes($message ) ;
		$time = date("Y-m-d H:i:s",time());
		$time_table = date("Ym",time());
		
		$table_pre = table_pre($groupname_) ;
		
	$sql_table = <<<EOT
CREATE TABLE IF NOT EXISTS `{$table_pre}common_log_{$time_table}` (
  `log_id` mediumint(8) NOT NULL auto_increment,
  `log_url` varchar(50) NOT NULL,
  `log_person` varchar(16) NOT NULL,
  `log_time` datetime NOT NULL,
  `log_ip` char(15) NOT NULL,
  `log_sql` text NOT NULL,
  `log_status` tinyint(1) NOT NULL default '1',
  `log_message` varchar(255) NOT NULL,
  PRIMARY KEY  (`log_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;		
EOT;
		$ci = &get_instance(); //初始化 为了用方法
		$d = $ci->load->database($groupname_,true);
		$d->query($sql_table);
		$sql_log = "INSERT INTO `{$table_pre}common_log_{$time_table}`(`log_url`,`log_person`,`log_time`,`log_ip`,`log_sql`,`log_status`,`log_message`)VALUES('{$url}','{$person}','{$time}','{$ip}','{$sql}','{$status}','{$message}')" ;
		$d->query($sql_log);
	}
}

/**
 * 将数据格式化成树形结构
 * @author CCC
 * @param array $items
 * @return array
 */
if(!function_exists("genTree9")){
	function genTree9($items,$id = 'id' ,$pid = 'pid' ,$child = 'children' ) {
	    $tree = array(); //格式化好的树
	    foreach ($items as $item)
	        if (isset($items[$item[$pid]]))
	            $items[$item[$pid]][$child][] = &$items[$item[$id]];
	        else
	            $tree[] = &$items[$item[$id]];
	    return $tree;
	}	
}
/**
 * 格式化select
 * @author CCC
 * @param array $parent
 * @deep int 层级关系 
 * @return array
 */
function getChildren($parent,$deep=0) {
		foreach($parent as $row) {
			$data[] = array("id"=>$row['id'], "name"=>$row['name'],"pid"=>$row['parentid'],'deep'=>$deep,'url'=>$row['url']);
			if (isset($row['childs']) && !empty($row['childs'])) {
				$data = array_merge($data, getChildren($row['childs'], $deep+1));
			}
		}
		return $data;
}

/**
 * 格式化select,生成options
 * @author CCC
 * @param array $parent
 * @deep int 层级关系 
 * @return array
 */
function getChildren2($parent,$deep=0,$id = 'id' , $pid = 'pid' ,$name = 'typename',$children = 'children') {
	foreach($parent as $row) {
		$data[] = array("id"=>$row[$id], "name"=>$row[$name],"pid"=>$row[$pid],'deep'=>$deep);
		if (isset($row[$children]) && !empty($row[$children])) {
			$data = array_merge($data, getChildren2($row[$children], $deep+1,$id,$pid,$name,$children));
		}
	}
	return $data;
}

/**
 * 格式化数组，用于分类缩进
 * @author CCC
 * @param array $list
 * @return array
 */	
function tree_format(&$list,$pid=0,$level=0,$html='--',$pid_string = 'pid' ,$id_string = 'id'){
	static $tree = array();		
	foreach($list as $v){
		if($v[$pid_string] == $pid){
			$v['sort'] = $level;
			$v['html'] = str_repeat($html,$level);
			$tree[] = $v;
			tree_format($list,$v[$id_string],$level+1,$html);
		} 
	}
	return $tree;
}

/**
 * 显示页面
 * @author CCC
 * @param string $message 错误信息
 * @param string $url 页面跳转地址
 * @param string $iserror 是否错误 1正确 0错误
 * @param string $timeout 时间
 * @param string $params 其他参数前面加? 例如?id=122&time=333
 */
if ( ! function_exists('showmessage')){
	
	function showMsg($message='',$url='',$iserror = 1,$params='',$top = '' ,$ky="" ,$timeout='3'){
		if($iserror == 1 ){//正确
			include APPPATH.'/errors/success.php';
		}else{
			include APPPATH.'/errors/fail.php';
		}
		exit();
	}	
}

/**
 * 获取后台登陆的数据，其中参数主要是为了 ，有时候用插件上传图片的时候 登陆状态消失
 * @author CCC
 * @param $string 解密的值
 * @return array
 */	
if(!function_exists("decode_data")){
	function decode_data($string = '' ){
		$data = array() ; 
		$encode_string = '' ; 
		$encode_string = ($string != "" )?$string:(isset($_COOKIE['admin_auth'])?$_COOKIE['admin_auth']:'') ; 
		if(empty($encode_string)){
			return $data ; 
		}
		
		$encode_string = auth_code($encode_string,"DECODE",config_item("s_key"));
		$data = unserialize($encode_string) ; 
		return $data ; 
	}
}

/**
 * 获取ids数据
 * @author CCC
 * @param $array array(1,3,4,5,6,7)
 * @return String 1,3,4,5,6,7
 */	
 if(!function_exists("get_ids")){
	 function get_ids($ids = '' ){
		if($ids){			
			$id = '' ; 
			for($i = 0 ; $i<count($ids) ; $i++){
				if(intval($ids[$i])<=0){continue ; }
				$id.=intval($ids[$i])."," ; 
			}
			$id = rtrim($id,",") ; 
			return $id ; 			
		}else{
			return '' ; 
		}	
	}
}

//获取 某个月的最大天数（最后一天）
function getMonthLastDay($month, $year) {
 	switch ($month) {
 		case 4 :
 		case 6 :
 		case 9 :
 		case 11 :
 			$days = 30;
 			break;
 		case 2 :
 			if ($year % 4 == 0) {
 				if ($year % 100 == 0) {
 					$days = $year % 400 == 0 ? 29 : 28;
 				} else {
 					$days = 29;
 				}
 			} else {
 				$days = 28;
 			}
 			break;
 		default :
 			$days = 31;
 			break;
 	}
	return $days;
}


/**
 * 通过生日记算年龄
 * @author fans
 * @date 2016-05-19
 */
function getAge( $birthday ){
	
	$age = date('Y', time()) - date('Y', strtotime($birthday)) - 1;
	if (date('m', time()) == date('m', strtotime($birthday))){ 
		if (date('d', time()) > date('d', strtotime($birthday))){  
			$age++;
		}  
	}elseif (date('m', time()) > date('m', strtotime($birthday))){  
		$age++;  
	}  
	
	return $age;
	
}


/**
 * 通过生日记算月龄
 * @author fans
 * @date 2016-05-19
 */
function getMonth( $birthday ){
	
	$age = date('Y', time()) - date('Y', strtotime($birthday)) - 1;
	$month = date('m', time()) - date('m', strtotime($birthday));
	
	if (date('m', time()) == date('m', strtotime($birthday))){ 
		if (date('d', time()) > date('d', strtotime($birthday))){  
			$age++;
		}  
	}elseif (date('m', time()) > date('m', strtotime($birthday))){  
		$age++;  
	}
	
	$month += $age * 12;
	
	return $month;
	
}
/**
 * 文件上传
 * @author fans
 * @date 2017-10-25
 */
function uploads()
{
	
}

?>
